package net.j4love.mybatis.example;

import net.j4love.mybatis.dao.UserDAO;
import net.j4love.mybatis.dto.UserQueryDTO;
import net.j4love.mybatis.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.List;

/**
 * @author he peng
 * @create 2017/11/23 15:37
 * @see
 */
public class OneLevelCacheTest {

    private static final Logger LOG = LoggerFactory.getLogger(OneLevelCacheTest.class);

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void onlySingleSessionSelect() throws Exception {
        SqlSession sqlSession = this.sqlSessionFactory.openSession(true);
        UserDAO userDAO = sqlSession.getMapper(UserDAO.class);
        UserQueryDTO query = new UserQueryDTO();
        query.setRealname("杰森伯恩");
        List<User> users0 = userDAO.selectList(query);

        LOG.info("first select ==> {} " , users0);

        List<User> users1 = userDAO.selectList(query);

        LOG.info("second select ==> {} " , users1);

    }


    @Test
    public void multiSessionSelect() throws Exception {

        UserQueryDTO query = new UserQueryDTO();
        query.setRealname("杰森伯恩");

        SqlSession sqlSession0 = this.sqlSessionFactory.openSession(true);
        UserDAO userDAO0 = sqlSession0.getMapper(UserDAO.class);
        List<User> users0 = userDAO0.selectList(query);

        LOG.info("session 1 select ==> {} " , users0);

        SqlSession sqlSession1 = this.sqlSessionFactory.openSession(true);
        UserDAO userDAO1 = sqlSession1.getMapper(UserDAO.class);
        List<User> users1 = userDAO1.selectList(query);

        LOG.info("session 2 select ==> {} " , users1);

    }

    @Test
    public void selectUpdateSelect() throws Exception {

        SqlSession sqlSession0 = this.sqlSessionFactory.openSession(true);
        UserDAO userDAO0 = sqlSession0.getMapper(UserDAO.class);
        User user0 = userDAO0.selectByPrimaryKey(1L);

        LOG.info("session 1 select ==> {} " , user0);

        SqlSession sqlSession1 = this.sqlSessionFactory.openSession(true);
        UserDAO userDAO1 = sqlSession1.getMapper(UserDAO.class);
        User user = new User();
        user.setId(1L);
        user.setNickname("肖申克的救赎");
        int i = userDAO1.updateNicknameByPrimaryKey(user);

        LOG.info("session 2 update ==> {} " , i);

        User user1 = userDAO0.selectByPrimaryKey(1L);

        LOG.info("session 1 select ==> {} " , user1);

    }
}
